<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AntSK 智能文档切片工具 - 语义文本切片服务</title>
    
    <!-- SEO 元标签 -->
    <meta name="description" content="AntSK智能文档切片工具，支持PDF、Word、TXT等多种格式文档的语义切片处理。基于AI语义理解，确保切片的语义完整性。">
    <meta name="keywords" content="文档切片,语义分析,文档处理,RAG,AI切片,文本分析">
    <meta name="author" content="AntSK Team">
    
    <!-- 预加载关键资源 -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: #7F7FFF;
            --primary-gradient: linear-gradient(135deg, #7F7FFF 0%, #8F8FFF 100%);
            --secondary-color: #f8f9ff;
            --accent-color: #667eea;
            --success-color: #10b981;
            --warning-color: #f59e0b;
            --error-color: #ef4444;
            --text-color: #333;
            --text-light: #666;
            --text-muted: #9ca3af;
            --background: #ffffff;
            --surface: rgba(255, 255, 255, 0.95);
            --border: #e0e6ff;
            --shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            --shadow-lg: 0 25px 50px rgba(127, 127, 255, 0.15);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: var(--text-color);
            background: linear-gradient(135deg, #f8f9ff 0%, #e6f3ff 50%, #f0f4ff 100%);
            min-height: 100vh;
        }

        /* 导航栏 */
        .navbar {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid var(--border);
            z-index: 1000;
            padding: 1rem 0;
        }

        .nav-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--primary-color);
            text-decoration: none;
        }

        .nav-links {
            display: flex;
            gap: 2rem;
            list-style: none;
        }

        .nav-links a {
            color: var(--text-color);
            text-decoration: none;
            font-weight: 500;
            transition: color 0.3s ease;
        }

        .nav-links a:hover {
            color: var(--primary-color);
        }

        /* 主容器 */
        .main-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 6rem 2rem 2rem;
        }

        .page-header {
            text-align: center;
            margin-bottom: 3rem;
        }

        .page-title {
            font-size: 3rem;
            font-weight: 700;
            margin-bottom: 1rem;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .page-subtitle {
            font-size: 1.2rem;
            color: var(--text-light);
            max-width: 600px;
            margin: 0 auto;
        }

        /* 标签页 */
        .tabs {
            background: white;
            border-radius: 20px;
            box-shadow: var(--shadow);
            overflow: hidden;
            margin-bottom: 2rem;
        }

        .tab-nav {
            display: flex;
            background: var(--secondary-color);
            border-bottom: 1px solid var(--border);
        }

        .tab-button {
            flex: 1;
            padding: 1.5rem 2rem;
            background: none;
            border: none;
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--text-light);
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
        }

        .tab-button.active {
            color: var(--primary-color);
            background: white;
        }

        .tab-button.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: var(--primary-gradient);
        }

        .tab-content {
            display: none;
            padding: 2rem;
        }

        .tab-content.active {
            display: block;
        }

        /* 文件上传区域 */
        .upload-area {
            border: 2px dashed var(--border);
            border-radius: 15px;
            padding: 3rem 2rem;
            text-align: center;
            margin-bottom: 2rem;
            transition: all 0.3s ease;
            cursor: pointer;
            background: var(--secondary-color);
        }

        .upload-area:hover, .upload-area.dragover {
            border-color: var(--primary-color);
            background: rgba(127, 127, 255, 0.05);
            transform: translateY(-2px);
        }

        .upload-icon {
            font-size: 3rem;
            color: var(--primary-color);
            margin-bottom: 1rem;
        }

        .upload-text {
            font-size: 1.1rem;
            color: var(--text-color);
            margin-bottom: 0.5rem;
        }

        .upload-hint {
            font-size: 0.9rem;
            color: var(--text-light);
        }

        .file-input {
            display: none;
        }

        .selected-file {
            background: white;
            border: 1px solid var(--border);
            border-radius: 10px;
            padding: 1rem;
            margin-top: 1rem;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .file-icon {
            font-size: 1.5rem;
            color: var(--primary-color);
        }

        .file-info {
            flex: 1;
        }

        .file-name {
            font-weight: 600;
            color: var(--text-color);
        }

        .file-size {
            font-size: 0.9rem;
            color: var(--text-light);
        }

        .remove-file {
            background: none;
            border: none;
            color: var(--error-color);
            cursor: pointer;
            font-size: 1.2rem;
            padding: 0.5rem;
            border-radius: 5px;
            transition: background-color 0.3s ease;
        }

        .remove-file:hover {
            background: rgba(239, 68, 68, 0.1);
        }

        /* 文本输入区域 */
        .text-input-area {
            margin-bottom: 2rem;
        }

        .text-input {
            width: 100%;
            min-height: 300px;
            padding: 1.5rem;
            border: 2px solid var(--border);
            border-radius: 15px;
            font-family: inherit;
            font-size: 1rem;
            line-height: 1.6;
            resize: vertical;
            transition: border-color 0.3s ease;
            background: white;
        }

        .text-input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(127, 127, 255, 0.1);
        }

        .text-counter {
            text-align: right;
            margin-top: 0.5rem;
            font-size: 0.9rem;
            color: var(--text-light);
        }

        /* 配置面板 */
        .config-panel {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: var(--shadow);
        }

        .config-title {
            font-size: 1.3rem;
            font-weight: 600;
            margin-bottom: 1.5rem;
            color: var(--text-color);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .config-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
        }

        .config-item {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .config-label {
            font-weight: 500;
            color: var(--text-color);
            font-size: 0.95rem;
        }

        .config-input {
            padding: 0.75rem 1rem;
            border: 2px solid var(--border);
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
            background: white;
        }

        .config-input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(127, 127, 255, 0.1);
        }

        .config-hint {
            font-size: 0.85rem;
            color: var(--text-light);
        }

        /* 配置标签容器 */
        .config-label-container {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        /* 提示问号样式 */
        .config-tooltip {
            position: relative;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 18px;
            height: 18px;
            background: var(--primary-color);
            color: white;
            border-radius: 50%;
            font-size: 12px;
            font-weight: 600;
            cursor: help;
            transition: all 0.3s ease;
        }

        .config-tooltip:hover {
            background: var(--accent-color);
            transform: scale(1.1);
        }

        /* 提示内容 */
        .config-tooltip-content {
            position: absolute;
            bottom: 130%;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.9);
            color: white;
            padding: 12px 16px;
            border-radius: 8px;
            font-size: 0.85rem;
            line-height: 1.4;
            white-space: nowrap;
            max-width: 300px;
            white-space: normal;
            width: max-content;
            min-width: 200px;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        /* 提示箭头 */
        .config-tooltip-content::after {
            content: '';
            position: absolute;
            top: 100%;
            left: 50%;
            transform: translateX(-50%);
            border: 6px solid transparent;
            border-top-color: rgba(0, 0, 0, 0.9);
        }

        /* 显示提示 */
        .config-tooltip:hover .config-tooltip-content {
            opacity: 1;
            visibility: visible;
        }

        .switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 26px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 26px;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 20px;
            width: 20px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked + .slider {
            background-color: var(--primary-color);
        }

        input:checked + .slider:before {
            transform: translateX(24px);
        }

        /* 处理按钮 */
        .process-button {
            background: var(--primary-gradient);
            color: white;
            border: none;
            padding: 1rem 3rem;
            border-radius: 30px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: var(--shadow-lg);
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin: 2rem auto;
        }

        .process-button:hover {
            transform: translateY(-3px);
            box-shadow: 0 30px 60px rgba(127, 127, 255, 0.25);
        }

        .process-button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        /* 加载状态 */
        .loading {
            display: none;
            text-align: center;
            padding: 2rem;
            color: var(--text-light);
        }

        .loading.show {
            display: block;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid var(--primary-color);
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 1rem;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 结果展示 */
        .results {
            display: none;
        }

        .results.show {
            display: block;
        }

        .results-header {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: var(--shadow);
        }

        .results-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 1rem;
            color: var(--text-color);
        }

        .results-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 1rem;
        }

        .stat-item {
            text-align: center;
            padding: 1rem;
            background: var(--secondary-color);
            border-radius: 10px;
        }

        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: var(--primary-color);
        }

        .stat-label {
            font-size: 0.9rem;
            color: var(--text-light);
            margin-top: 0.5rem;
        }

        .chunks-container {
            display: grid;
            gap: 1.5rem;
        }

        .chunk-card {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            box-shadow: var(--shadow);
            border-left: 4px solid var(--primary-color);
        }

        .chunk-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .chunk-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--text-color);
        }

        .chunk-meta {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .meta-item {
            background: var(--secondary-color);
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.85rem;
            color: var(--text-color);
        }

        .chunk-content {
            background: #f9fafb;
            padding: 1.5rem;
            border-radius: 10px;
            border: 1px solid var(--border);
            font-family: 'JetBrains Mono', 'Consolas', monospace;
            font-size: 0.9rem;
            line-height: 1.6;
            color: var(--text-color);
            white-space: pre-wrap;
            word-wrap: break-word;
            max-height: 300px;
            overflow-y: auto;
        }

        /* 表格内容样式 */
        .chunk-content.table-content {
            font-family: inherit;
            white-space: pre-wrap; /* 保持换行符显示 */
        }

        /* 表格内的文本保持正常换行 */
        .chunk-content.table-content table {
            white-space: normal;
        }

        .chunk-content table {
            width: 100%;
            border-collapse: collapse;
            margin: 1rem 0;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .chunk-content table th,
        .chunk-content table td {
            padding: 0.75rem 1rem;
            text-align: left;
            border-bottom: 1px solid var(--border);
            font-size: 0.9rem;
        }

        .chunk-content table th {
            background: var(--secondary-color);
            font-weight: 600;
            color: var(--text-color);
            border-bottom: 2px solid var(--primary-color);
        }

        .chunk-content table tr:hover {
            background: rgba(127, 127, 255, 0.05);
        }

        .chunk-content table tr:last-child td {
            border-bottom: none;
        }

        /* 表格标识 */
        .table-indicator {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            background: rgba(127, 127, 255, 0.1);
            color: var(--primary-color);
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: 500;
            margin-bottom: 1rem;
        }

        .semantic-score {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .score-bar {
            width: 100px;
            height: 6px;
            background: #e5e7eb;
            border-radius: 3px;
            overflow: hidden;
        }

        .score-fill {
            height: 100%;
            background: var(--primary-gradient);
            transition: width 0.3s ease;
        }

        /* 错误提示 */
        .error-message {
            background: #fee2e2;
            color: var(--error-color);
            padding: 1rem 1.5rem;
            border-radius: 10px;
            border: 1px solid #fecaca;
            margin: 1rem 0;
            display: none;
        }

        .error-message.show {
            display: block;
        }

        /* 成功提示 */
        .success-message {
            background: #d1fae5;
            color: var(--success-color);
            padding: 1rem 1.5rem;
            border-radius: 10px;
            border: 1px solid #a7f3d0;
            margin: 1rem 0;
            display: none;
        }

        .success-message.show {
            display: block;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .nav-container {
                padding: 0 1rem;
            }

            .nav-links {
                display: none;
            }

            .main-container {
                padding: 6rem 1rem 2rem;
            }

            .page-title {
                font-size: 2.5rem;
            }

            .tab-nav {
                flex-direction: column;
            }

            .tab-button {
                text-align: center;
            }

            .config-grid {
                grid-template-columns: 1fr;
            }

            .chunk-header {
                flex-direction: column;
                align-items: flex-start;
            }
        }

        /* 动画效果 */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .fade-in {
            animation: fadeInUp 0.6s ease forwards;
        }

        /* === 轻量缩小整体布局与字体（约 8-12%） === */
        html { font-size: 15px; } /* 由默认16px调整为15px，rem整体略缩 */
        body { font-size: 0.95rem; }

        /* 顶部导航与标题 */
        .navbar { padding: 0.75rem 0; }
        .nav-container { padding: 0 1.5rem; }
        .logo { font-size: 1.35rem; }
        .nav-links { gap: 1.5rem; }
        .main-container { padding: 5rem 1.5rem 1.5rem; }
        .page-title { font-size: 2.6rem; }
        .page-subtitle { font-size: 1.05rem; }

        /* 标签页导航 */
        .tab-button { padding: 1.25rem 1.5rem; font-size: 1rem; }

        /* 上传区域与文件信息 */
        .upload-area { padding: 2.5rem 1.5rem; border-radius: 12px; }
        .upload-icon { font-size: 2.6rem; }
        .selected-file { padding: 0.85rem; border-radius: 8px; }
        .file-icon { font-size: 1.3rem; }
        .remove-file { font-size: 1.05rem; }

        /* 文本输入区域 */
        .text-input { min-height: 260px; padding: 1.25rem; font-size: 0.95rem; }
        .text-counter { font-size: 0.85rem; }

        /* 配置面板 */
        .config-panel { padding: 1.5rem; border-radius: 12px; }
        .config-title { font-size: 1.2rem; }
        .config-input { padding: 0.65rem 0.9rem; font-size: 0.95rem; }
        .config-hint { font-size: 0.8rem; }

        /* 开关尺寸微调 */
        .switch { width: 46px; height: 24px; }
        .slider:before { height: 18px; width: 18px; left: 3px; bottom: 3px; }
        input:checked + .slider:before { transform: translateX(22px); }

        /* 处理按钮 */
        .process-button { padding: 0.9rem 2.2rem; font-size: 1rem; border-radius: 26px; }

        /* 加载与提示 */
        .spinner { width: 34px; height: 34px; border-width: 3px; }
        .error-message, .success-message { padding: 0.8rem 1.2rem; border-radius: 8px; }

        /* 结果展示 */
        .results-header { padding: 1.5rem; }
        .results-title { font-size: 1.35rem; }
        .stat-value { font-size: 1.75rem; }
        .chunk-card { padding: 1.5rem; border-radius: 12px; }
        .chunk-title { font-size: 1rem; }
        .chunk-content { font-size: 0.85rem; padding: 1.2rem; max-height: 260px; }
        .score-bar { width: 90px; height: 5px; }

        /* 移动端保持协调的同时继续小幅缩小 */
        @media (max-width: 768px) {
            .main-container { padding: 5rem 1rem 1.25rem; }
            .page-title { font-size: 2.2rem; }
            .tab-button { padding: 1rem 1.25rem; }
            .upload-area { padding: 2rem 1.25rem; }
            .config-panel { padding: 1.25rem; }
            .chunk-content { max-height: 220px; }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar">
        <div class="nav-container">
            <a href="/home" class="logo">
                🔥 AntSK FileChunk
            </a>
            <ul class="nav-links">
                <li><a href="/home">首页</a></li>
                <li><a href="/docs">API文档</a></li>
                <li><a href="https://tree456.com/#products" target="_blank">其他产品</a></li>
                <li><a href="https://github.com/xuzeyu91/AntSK-FileChunk" target="_blank">GitHub</a></li>
            </ul>
        </div>
    </nav>

    <!-- 主容器 -->
    <div class="main-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <h1 class="page-title">智能文档切片工具</h1>
            <p class="page-subtitle">
                上传文档或输入文本，体验基于语义理解的智能文档切片服务
            </p>
        </div>

        <!-- 标签页 -->
        <div class="tabs">
            <div class="tab-nav">
                <button class="tab-button active" onclick="switchTab('file')">
                    📁 文件上传
                </button>
                <button class="tab-button" onclick="switchTab('text')">
                    📝 文本输入
                </button>
                <button class="tab-button" onclick="switchTab('api')">
                    📚 API说明
                </button>
            </div>

            <!-- 文件上传标签页 -->
            <div class="tab-content active" id="file-tab">
                <div class="upload-area" onclick="document.getElementById('fileInput').click()">
                    <div class="upload-icon">📎</div>
                    <div class="upload-text">点击选择文件或拖拽文件到此处</div>
                    <div class="upload-hint">支持 PDF、Word(.docx)、纯文本(.txt) 格式，最大 50MB</div>
                </div>
                <input type="file" id="fileInput" class="file-input" accept=".pdf,.docx,.doc,.txt" onchange="handleFileSelect(event)">
                <div id="selectedFile" class="selected-file" style="display: none;">
                    <div class="file-icon">📄</div>
                    <div class="file-info">
                        <div class="file-name" id="fileName"></div>
                        <div class="file-size" id="fileSize"></div>
                    </div>
                    <button class="remove-file" onclick="removeFile()">×</button>
                </div>
            </div>

            <!-- 文本输入标签页 -->
            <div class="tab-content" id="text-tab">
                <div class="text-input-area">
                    <textarea 
                        id="textInput" 
                        class="text-input" 
                        placeholder="请输入要进行语义切片的文本内容..."
                        oninput="updateTextCounter()"
                    ></textarea>
                    <div class="text-counter">
                        <span id="textCount">0</span> 字符
                    </div>
                </div>
            </div>

            <!-- API说明标签页 -->
            <div class="tab-content" id="api-tab">
                <div style="background: white; padding: 2rem; border-radius: 15px;">
                    <h3 style="margin-bottom: 1rem; color: var(--text-color);">📚 API接口说明</h3>
                    
                    <h4 style="margin: 1.5rem 0 0.5rem; color: var(--primary-color);">文件处理接口</h4>
                    <div style="background: #f9fafb; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;">
                        <code>POST /api/process-file</code>
                    </div>
                    <p style="color: var(--text-light); margin-bottom: 1rem;">
                        上传文件进行语义切片处理，支持PDF、Word、TXT格式。
                    </p>
                    
                    <h4 style="margin: 1.5rem 0 0.5rem; color: var(--primary-color);">文本处理接口</h4>
                    <div style="background: #f9fafb; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;">
                        <code>POST /api/process-text</code>
                    </div>
                    <p style="color: var(--text-light); margin-bottom: 1rem;">
                        直接处理文本内容进行语义切片。
                    </p>
                    
                    <h4 style="margin: 1.5rem 0 0.5rem; color: var(--primary-color);">获取默认配置</h4>
                    <div style="background: #f9fafb; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;">
                        <code>GET /api/config/default</code>
                    </div>
                    <p style="color: var(--text-light); margin-bottom: 1rem;">
                        获取系统默认的切片配置参数。
                    </p>
                    
                    <p style="color: var(--text-light);">
                        更多详细信息请访问 <a href="/docs" target="_blank" style="color: var(--primary-color);">Swagger API文档</a>
                    </p>
                </div>
            </div>
        </div>

        <!-- 配置面板 -->
        <div class="config-panel">
            <h3 class="config-title">
                ⚙️ 切片配置参数
            </h3>
            <div class="config-grid">
                <div class="config-item">
                    <div class="config-label-container">
                        <label class="config-label">目标切片大小</label>
                        <div class="config-tooltip">
                            ?
                            <div class="config-tooltip-content">
                                理想的文本切片字符数目标。系统会尽量将文本切分到接近这个长度，同时保持语义完整性。较大的目标值会产生更长的切片，包含更多上下文信息。
                            </div>
                        </div>
                    </div>
                    <input type="number" id="targetChunkSize" class="config-input" value="800" min="200" max="2000">
                    <div class="config-hint">推荐范围: 600-1200 字符</div>
                </div>
                <div class="config-item">
                    <div class="config-label-container">
                        <label class="config-label">最小切片大小</label>
                        <div class="config-tooltip">
                            ?
                            <div class="config-tooltip-content">
                                单个文本切片的最小字符数。低于此长度的切片会被合并到相邻切片中，确保每个切片都有足够的信息量。设置过小可能产生信息不完整的切片。
                            </div>
                        </div>
                    </div>
                    <input type="number" id="minChunkSize" class="config-input" value="200" min="50" max="1000">
                    <div class="config-hint">最小 50 字符</div>
                </div>
                <div class="config-item">
                    <div class="config-label-container">
                        <label class="config-label">最大切片大小</label>
                        <div class="config-tooltip">
                            ?
                            <div class="config-tooltip-content">
                                单个文本切片的最大字符数限制。超过此长度的文本段会被强制切分，即使可能破坏语义完整性。防止单个切片过长影响处理效率。
                            </div>
                        </div>
                    </div>
                    <input type="number" id="maxChunkSize" class="config-input" value="1500" min="500" max="5000">
                    <div class="config-hint">最大 5000 字符</div>
                </div>
                <div class="config-item">
                    <div class="config-label-container">
                        <label class="config-label">语义相似度阈值</label>
                        <div class="config-tooltip">
                            ?
                            <div class="config-tooltip-content">
                                判断相邻文本段是否应该合并的语义相似度门槛。值越高表示要求越严格，只有高度相关的内容才会被合并。较低的值会产生更长但可能主题分散的切片。
                            </div>
                        </div>
                    </div>
                    <input type="number" id="semanticThreshold" class="config-input" value="0.7" min="0" max="1" step="0.1">
                    <div class="config-hint">0.0-1.0，越高越严格</div>
                </div>
                <div class="config-item">
                    <div class="config-label-container">
                        <label class="config-label">段落合并阈值</label>
                        <div class="config-tooltip">
                            ?
                            <div class="config-tooltip-content">
                                决定相邻段落是否应该合并成一个切片的相似度阈值。高阈值保持段落独立性，低阈值允许相关段落合并，创建更有上下文的切片。
                            </div>
                        </div>
                    </div>
                    <input type="number" id="paragraphMergeThreshold" class="config-input" value="0.8" min="0" max="1" step="0.1">
                    <div class="config-hint">用于判断段落是否应合并，0.0-1.0</div>
                </div>
                <div class="config-item">
                    <div class="config-label-container">
                        <label class="config-label">重叠比例</label>
                        <div class="config-tooltip">
                            ?
                            <div class="config-tooltip-content">
                                相邻切片之间重叠内容的比例。重叠可以保持上下文连续性，提高信息检索的准确性。较高的重叠比例会增加总体数据量但提供更好的语义连接。
                            </div>
                        </div>
                    </div>
                    <input type="number" id="overlapRatio" class="config-input" value="0.1" min="0" max="0.5" step="0.05">
                    <div class="config-hint">切片间重叠比例</div>
                </div>
                <div class="config-item">
                    <div class="config-label-container">
                        <label class="config-label">语言设置</label>
                        <div class="config-tooltip">
                            ?
                            <div class="config-tooltip-content">
                                指定文档的主要语言，影响文本分词、语义分析和句子边界检测。正确的语言设置能显著提高切片质量和语义理解准确性。
                            </div>
                        </div>
                    </div>
                    <select id="language" class="config-input">
                        <option value="zh">中文</option>
                        <option value="en">英文</option>
                    </select>
                    <div class="config-hint">选择文档主要语言</div>
                </div>
                <br/>
                <div class="config-item">
                    <div class="config-label-container">
                        <label class="config-label">保持文档结构</label>
                        <div class="config-tooltip">
                            ?
                            <div class="config-tooltip-content">
                                启用后会识别并保持文档的层级结构（如标题、章节、段落），确保切片边界不会破坏重要的文档组织结构，保持内容的逻辑完整性。
                            </div>
                        </div>
                    </div>
                    <label class="switch">
                        <input type="checkbox" id="preserveStructure" checked>
                        <span class="slider"></span>
                    </label>
                    <div class="config-hint">保持章节段落结构</div>
                </div>
                <div class="config-item">
                    <div class="config-label-container">
                        <label class="config-label">处理特殊内容</label>
                        <div class="config-tooltip">
                            ?
                            <div class="config-tooltip-content">
                                启用后会特别处理表格、代码块、公式、列表等特殊内容，确保这些结构化内容的完整性，避免在特殊内容中间进行切分。
                            </div>
                        </div>
                    </div>
                    <label class="switch">
                        <input type="checkbox" id="handleSpecialContent" checked>
                        <span class="slider"></span>
                    </label>
                    <div class="config-hint">处理表格、图片等</div>
                </div>
            </div>
        </div>

        <!-- 处理按钮 -->
        <button class="process-button" id="processBtn" onclick="processDocument()">
            🚀 开始智能切片
        </button>

        <!-- 错误提示 -->
        <div class="error-message" id="errorMessage"></div>

        <!-- 成功提示 -->
        <div class="success-message" id="successMessage"></div>

        <!-- 加载状态 -->
        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p>正在进行语义分析和智能切片...</p>
        </div>

        <!-- 结果展示 -->
        <div class="results" id="results">
            <div class="results-header">
                <h2 class="results-title">切片结果</h2>
                <div class="results-stats" id="resultsStats">
                    <!-- 统计信息将通过JavaScript填充 -->
                </div>
            </div>
            <div class="chunks-container" id="chunksContainer">
                <!-- 切片结果将通过JavaScript填充 -->
            </div>
        </div>
    </div>

    <script>
        let selectedFile = null;

        // 标签页切换
        function switchTab(tabName) {
            // 隐藏所有标签页内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 移除所有按钮的激活状态
            document.querySelectorAll('.tab-button').forEach(button => {
                button.classList.remove('active');
            });
            
            // 显示选中的标签页内容
            document.getElementById(tabName + '-tab').classList.add('active');
            
            // 激活对应的按钮
            event.target.classList.add('active');
        }

        // 文件选择处理
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (file) {
                selectedFile = file;
                showSelectedFile(file);
            }
        }

        // 显示选中的文件
        function showSelectedFile(file) {
            const selectedFileDiv = document.getElementById('selectedFile');
            const fileName = document.getElementById('fileName');
            const fileSize = document.getElementById('fileSize');
            
            fileName.textContent = file.name;
            fileSize.textContent = formatFileSize(file.size);
            selectedFileDiv.style.display = 'flex';
        }

        // 移除文件
        function removeFile() {
            selectedFile = null;
            document.getElementById('selectedFile').style.display = 'none';
            document.getElementById('fileInput').value = '';
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 更新文本计数器
        function updateTextCounter() {
            const textInput = document.getElementById('textInput');
            const textCount = document.getElementById('textCount');
            textCount.textContent = textInput.value.length;
        }

        // 拖拽上传处理
        const uploadArea = document.querySelector('.upload-area');

        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                const file = files[0];
                if (isValidFile(file)) {
                    selectedFile = file;
                    showSelectedFile(file);
                } else {
                    showError('不支持的文件格式，请上传 PDF、Word 或 TXT 文件');
                }
            }
        });

        // 验证文件类型
        function isValidFile(file) {
            const validTypes = ['.pdf', '.docx', '.doc', '.txt'];
            const fileExt = '.' + file.name.split('.').pop().toLowerCase();
            return validTypes.includes(fileExt);
        }

        // 获取配置参数
        function getConfig() {
            return {
                min_chunk_size: parseInt(document.getElementById('minChunkSize').value),
                max_chunk_size: parseInt(document.getElementById('maxChunkSize').value),
                target_chunk_size: parseInt(document.getElementById('targetChunkSize').value),
                semantic_threshold: parseFloat(document.getElementById('semanticThreshold').value),
                paragraph_merge_threshold: parseFloat(document.getElementById('paragraphMergeThreshold').value),
                overlap_ratio: parseFloat(document.getElementById('overlapRatio').value),
                language: document.getElementById('language').value,
                preserve_structure: document.getElementById('preserveStructure').checked,
                handle_special_content: document.getElementById('handleSpecialContent').checked
            };
        }

        // 处理文档
        async function processDocument() {
            // 检查输入
            const activeTab = document.querySelector('.tab-content.active').id;
            const isFileTab = activeTab === 'file-tab';
            const isTextTab = activeTab === 'text-tab';

            if (isFileTab && !selectedFile) {
                showError('请选择要处理的文件');
                return;
            }

            if (isTextTab) {
                const textInput = document.getElementById('textInput').value.trim();
                if (!textInput) {
                    showError('请输入要处理的文本内容');
                    return;
                }
            }

            // 显示加载状态
            showLoading(true);
            hideError();
            hideSuccess();
            hideResults();

            try {
                let response;
                const config = getConfig();

                if (isFileTab) {
                    // 文件处理
                    const formData = new FormData();
                    formData.append('file', selectedFile);
                    formData.append('config', JSON.stringify(config));

                    response = await fetch('/api/process-file', {
                        method: 'POST',
                        body: formData
                    });
                } else {
                    // 文本处理
                    const textInput = document.getElementById('textInput').value;
                    const formData = new FormData();
                    formData.append('text', textInput);
                    formData.append('config', JSON.stringify(config));

                    response = await fetch('/api/process-text', {
                        method: 'POST',
                        body: formData
                    });
                }

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.detail || '处理失败');
                }

                const result = await response.json();
                
                if (result.success) {
                    showSuccess(`处理完成！共生成 ${result.total_chunks} 个切片，耗时 ${result.processing_time.toFixed(2)} 秒`);
                    showResults(result);
                } else {
                    throw new Error(result.message || '处理失败');
                }

            } catch (error) {
                console.error('处理错误:', error);
                showError('处理失败: ' + error.message);
            } finally {
                showLoading(false);
            }
        }

        // 显示/隐藏加载状态
        function showLoading(show) {
            const loading = document.getElementById('loading');
            const processBtn = document.getElementById('processBtn');
            
            if (show) {
                loading.classList.add('show');
                processBtn.disabled = true;
                processBtn.textContent = '处理中...';
            } else {
                loading.classList.remove('show');
                processBtn.disabled = false;
                processBtn.innerHTML = '🚀 开始智能切片';
            }
        }

        // 显示错误信息
        function showError(message) {
            const errorDiv = document.getElementById('errorMessage');
            errorDiv.textContent = message;
            errorDiv.classList.add('show');
            setTimeout(() => {
                errorDiv.classList.remove('show');
            }, 5000);
        }

        // 隐藏错误信息
        function hideError() {
            document.getElementById('errorMessage').classList.remove('show');
        }

        // 显示成功信息
        function showSuccess(message) {
            const successDiv = document.getElementById('successMessage');
            successDiv.textContent = message;
            successDiv.classList.add('show');
            setTimeout(() => {
                successDiv.classList.remove('show');
            }, 5000);
        }

        // 隐藏成功信息
        function hideSuccess() {
            document.getElementById('successMessage').classList.remove('show');
        }

        // Markdown表格转HTML表格
        function markdownTableToHtml(content) {
            // 处理表格内容标记格式 [表格内容] ...
            if (content.includes('[表格内容]')) {
                return parseTableContentFormat(content);
            }
            
            // 处理标准markdown表格格式
            const tableRegex = /\|(.+)\|\s*\n\|[\s\-\|:]+\|\s*\n((?:\|.+\|\s*\n?)*)/g;
            
            // 首先转义HTML，保持换行符
            let processedContent = escapeHtml(content);
            
            // 然后将markdown表格转换为HTML表格
            processedContent = processedContent.replace(tableRegex, (match, header, rows) => {
                // 解析表头（需要反转义以正确处理）
                const headerCells = unescapeHtml(header).split('|').map(cell => cell.trim()).filter(cell => cell);
                
                // 解析数据行（需要反转义以正确处理）
                const dataRows = unescapeHtml(rows).trim().split('\n').map(row => {
                    return row.split('|').map(cell => cell.trim()).filter(cell => cell);
                }).filter(row => row.length > 0);
                
                // 生成HTML表格
                let html = '<table>';
                
                // 表头
                if (headerCells.length > 0) {
                    html += '<thead><tr>';
                    headerCells.forEach(cell => {
                        html += `<th>${escapeHtml(cell)}</th>`;
                    });
                    html += '</tr></thead>';
                }
                
                // 表体
                if (dataRows.length > 0) {
                    html += '<tbody>';
                    dataRows.forEach(row => {
                        html += '<tr>';
                        row.forEach((cell, index) => {
                            html += `<td>${escapeHtml(cell)}</td>`;
                        });
                        // 如果行的列数少于表头，补充空列
                        for (let i = row.length; i < headerCells.length; i++) {
                            html += '<td></td>';
                        }
                        html += '</tr>';
                    });
                    html += '</tbody>';
                }
                
                html += '</table>';
                return html;
            });
            
            return processedContent;
        }

        // 解析 [表格内容] 格式的表格
        function parseTableContentFormat(content) {
            // 移除 [表格内容] 标记，保留换行符
            let tableContent = content.replace(/\[表格内容\]\s*/, '').trim();
            
            // 先检查是否是标准markdown表格格式（包含换行的）
            if (tableContent.includes('|') && tableContent.includes('---')) {
                // 尝试解析标准markdown表格
                const lines = tableContent.split('\n').map(line => line.trim()).filter(line => line);
                if (lines.length >= 3) {
                    // 检查是否有合法的markdown表格结构
                    const hasHeaderRow = lines[0].includes('|');
                    const hasSeparatorRow = lines[1] && lines[1].includes('---');
                    const hasDataRows = lines.length > 2 && lines[2].includes('|');
                    
                    if (hasHeaderRow && hasSeparatorRow && hasDataRows) {
                        return parseStandardMarkdownTable(tableContent);
                    }
                }
            }
            
            // 格式1: 检查是否是编号列表格式（如 "1 项目A 描述A 2 项目B 描述B"）
            if (tableContent.match(/\d+\s+\S+.*?\d+\s+\S+/)) {
                return parseNumberedListTable(tableContent);
            }
            
            // 格式2: 键值对格式 "key: value | key: value"
            if (tableContent.includes(':') && tableContent.includes('|')) {
                return parseKeyValueTable(tableContent);
            }
            
            // 格式3: 标准markdown表格（可能被压缩在一行）
            if (tableContent.includes('---')) {
                return parseCompressedMarkdownTable(tableContent);
            }
            
            // 格式4: 简单的管道分隔格式
            if (tableContent.includes('|')) {
                return parseSimplePipeTable(tableContent);
            }
            
            // 如果无法解析，返回原始内容
            return escapeHtml(content);
        }
        
        // 解析标准markdown表格
        function parseStandardMarkdownTable(content) {
            try {
                const lines = content.split('\n').map(line => line.trim()).filter(line => line);
                const tableData = [];
                
                for (let i = 0; i < lines.length; i++) {
                    const line = lines[i];
                    
                    // 跳过分隔行
                    if (line.includes('---')) {
                        continue;
                    }
                    
                    // 解析表格行
                    if (line.includes('|')) {
                        const cells = line.split('|')
                            .map(cell => cell.trim())
                            .filter((cell, index, array) => {
                                // 移除首尾的空单元格
                                return !(index === 0 && cell === '') && !(index === array.length - 1 && cell === '');
                            });
                        
                        if (cells.length > 0) {
                            // 确保有至少3列
                            while (cells.length < 3) {
                                cells.push('');
                            }
                            tableData.push(cells.slice(0, 3)); // 只取前3列
                        }
                    }
                }
                
                if (tableData.length >= 1) {
                    let html = '<table>';
                    
                    // 表头
                    if (tableData.length >= 1) {
                        html += '<thead><tr>';
                        tableData[0].forEach(cell => {
                            html += `<th>${escapeHtml(cell)}</th>`;
                        });
                        html += '</tr></thead>';
                    }
                    
                    // 数据行
                    if (tableData.length > 1) {
                        html += '<tbody>';
                        for (let i = 1; i < tableData.length; i++) {
                            html += '<tr>';
                            tableData[i].forEach(cell => {
                                html += `<td>${escapeHtml(cell)}</td>`;
                            });
                            html += '</tr>';
                        }
                        html += '</tbody>';
                    }
                    
                    html += '</table>';
                    return html;
                }
                
                return escapeHtml(content);
            } catch (e) {
                console.error('解析标准markdown表格失败:', e);
                return escapeHtml(content);
            }
        }

        // 解析编号列表格式的表格
        function parseNumberedListTable(content) {
            try {
                // 更精确的正则表达式，匹配编号和后续内容
                const numberPattern = /(\d+)\s+([^\d]+?)(?=\s*\d+\s+|$)/g;
                const matches = [];
                let match;
                
                // 重置正则表达式的lastIndex
                numberPattern.lastIndex = 0;
                
                while ((match = numberPattern.exec(content)) !== null) {
                    const number = match[1];
                    let text = match[2].trim();
                    
                    // 清理文本中的管道符和多余空格
                    text = text.replace(/\|\s*$/, '').replace(/^\|\s*/, '').trim();
                    text = text.replace(/\s+/g, ' '); // 合并多个空格
                    
                    if (text) {
                        matches.push([number, text]);
                    }
                }
                
                // 如果没有匹配到编号格式，尝试按管道符分割
                if (matches.length === 0) {
                    const parts = content.split('|').map(part => part.trim()).filter(part => part);
                    if (parts.length >= 3) {
                        // 按3个一组处理
                        for (let i = 0; i < parts.length; i += 3) {
                            const group = parts.slice(i, i + 3);
                            if (group.length >= 2) {
                                matches.push([group[0] || (i/3 + 1).toString(), group[1] || '', group[2] || '']);
                            }
                        }
                    }
                }
                
                if (matches.length > 0) {
                    const tableData = [];
                    
                    matches.forEach(([number, text]) => {
                        let question = '';
                        let example = '';
                        
                        // 如果已经是三列数据
                        if (Array.isArray(text)) {
                            question = text[0] || '';
                            example = text[1] || '';
                        } else {
                            // 尝试分析文本结构
                            const questionMarkIndex = text.indexOf('?');
                            if (questionMarkIndex > 0) {
                                question = text.substring(0, questionMarkIndex + 1).trim();
                                let remaining = text.substring(questionMarkIndex + 1).trim();
                                
                                // 查找"示例:"后的内容
                                const exampleMatch = remaining.match(/示例[：:]\s*(.+)/);
                                if (exampleMatch) {
                                    example = exampleMatch[1].trim();
                                } else {
                                    example = remaining;
                                }
                            } else {
                                // 没有问号，尝试按空格或其他分隔符分割
                                const parts = text.split(/[\s]{2,}|[，。；]/)
                                    .map(p => p.trim())
                                    .filter(p => p);
                                
                                if (parts.length >= 2) {
                                    question = parts[0];
                                    example = parts.slice(1).join(' ');
                                } else {
                                    question = text;
                                    example = '';
                                }
                            }
                        }
                        
                        // 清理内容
                        question = question.replace(/^[\s|]+|[\s|]+$/g, '');
                        example = example.replace(/^[\s|]+|[\s|]+$/g, '');
                        
                        tableData.push([number, question, example]);
                    });
                    
                    if (tableData.length > 0) {
                        let html = '<table>';
                        
                        // 生成表头
                        html += '<thead><tr>';
                        html += '<th>编号</th>';
                        html += '<th>检查项</th>';
                        html += '<th>描述</th>';
                        html += '</tr></thead>';
                        
                        // 生成数据行
                        html += '<tbody>';
                        tableData.forEach(row => {
                            html += '<tr>';
                            html += `<td>${escapeHtml(row[0] || '')}</td>`;
                            html += `<td>${escapeHtml(row[1] || '')}</td>`;
                            html += `<td>${escapeHtml(row[2] || '')}</td>`;
                            html += '</tr>';
                        });
                        html += '</tbody></table>';
                        
                        return html;
                    }
                }
                
                return escapeHtml(content);
            } catch (e) {
                console.error('解析编号列表表格失败:', e);
                return escapeHtml(content);
            }
        }

        // 解析键值对表格
        function parseKeyValueTable(content) {
            try {
                // 清理内容，移除多余的管道符
                let cleanContent = content.replace(/\|\s*$/, '').replace(/^\s*\|/, '');
                const pairs = cleanContent.split('|').map(pair => pair.trim()).filter(pair => pair);
                
                let html = '<table>';
                html += '<thead><tr><th>字段</th><th>值</th></tr></thead>';
                html += '<tbody>';
                
                pairs.forEach(pair => {
                    const colonIndex = pair.indexOf(':');
                    if (colonIndex > 0) {
                        const key = pair.substring(0, colonIndex).trim();
                        const value = pair.substring(colonIndex + 1).trim();
                        
                        // 进一步清理值中的管道符
                        const cleanValue = value.replace(/\|\s*$/, '').trim();
                        
                        html += `<tr><td>${escapeHtml(key)}</td><td>${escapeHtml(cleanValue)}</td></tr>`;
                    } else if (pair.trim()) {
                        // 没有冒号的内容，作为单独的信息行
                        html += `<tr><td colspan="2">${escapeHtml(pair)}</td></tr>`;
                    }
                });
                
                html += '</tbody></table>';
                return html;
            } catch (e) {
                console.error('解析键值对表格失败:', e);
                return escapeHtml(content);
            }
        }

        // 解析压缩的markdown表格
        function parseCompressedMarkdownTable(content) {
            try {
                // 尝试重建表格结构
                const parts = content.split(/\s+/);
                const separatorIndex = parts.findIndex(part => part.includes('---'));
                
                if (separatorIndex > 0) {
                    const headerParts = parts.slice(0, separatorIndex);
                    const dataParts = parts.slice(separatorIndex + 1);
                    
                    // 估算列数（基于分隔符）
                    const separatorPart = parts[separatorIndex];
                    const colCount = (separatorPart.match(/---/g) || []).length;
                    
                    if (colCount > 0) {
                        let html = '<table>';
                        
                        // 构建表头
                        html += '<thead><tr>';
                        for (let i = 0; i < Math.min(colCount, headerParts.length); i++) {
                            html += `<th>${escapeHtml(headerParts[i])}</th>`;
                        }
                        html += '</tr></thead>';
                        
                        // 构建数据行
                        html += '<tbody>';
                        for (let i = 0; i < dataParts.length; i += colCount) {
                            html += '<tr>';
                            for (let j = 0; j < colCount; j++) {
                                const cellData = dataParts[i + j] || '';
                                html += `<td>${escapeHtml(cellData)}</td>`;
                            }
                            html += '</tr>';
                        }
                        html += '</tbody></table>';
                        
                        return html;
                    }
                }
                
                return escapeHtml(content);
            } catch (e) {
                return escapeHtml(content);
            }
        }

        // 解析简单的管道分隔表格
        function parseSimplePipeTable(content) {
            try {
                const parts = content.split('|').map(part => part.trim()).filter(part => part);
                
                if (parts.length >= 3) {
                    const colCount = 3; // 固定3列
                    const tableData = [];
                    
                    // 检查第一部分是否包含表头关键词
                    const hasHeader = parts[0] && /编号|检查项|描述|项目|内容|序号/.test(parts[0]);
                    
                    if (hasHeader) {
                        // 第一部分是表头描述，需要解析
                        const headerParts = parts[0].split(/\s+/).filter(p => p.trim());
                        if (headerParts.length >= 2) {
                            // 使用解析出的表头
                            const headers = headerParts.slice(0, 3);
                            while (headers.length < 3) {
                                headers.push('描述');
                            }
                            tableData.push(headers);
                            
                            // 处理剩余数据
                            const remainingParts = parts.slice(1);
                            for (let i = 0; i < remainingParts.length; i += colCount) {
                                const row = [];
                                for (let j = 0; j < colCount; j++) {
                                    row.push(remainingParts[i + j] || '');
                                }
                                tableData.push(row);
                            }
                        } else {
                            // 使用默认表头
                            tableData.push(['编号', '检查项', '描述']);
                            
                            // 处理所有数据
                            for (let i = 0; i < parts.length; i += colCount) {
                                const row = [];
                                for (let j = 0; j < colCount; j++) {
                                    row.push(parts[i + j] || '');
                                }
                                tableData.push(row);
                            }
                        }
                    } else {
                        // 没有明确表头，使用默认表头
                        tableData.push(['编号', '检查项', '描述']);
                        
                        // 处理所有数据
                        for (let i = 0; i < parts.length; i += colCount) {
                            const row = [];
                            for (let j = 0; j < colCount; j++) {
                                row.push(parts[i + j] || '');
                            }
                            if (row.some(cell => cell.trim())) { // 至少有一个非空单元格
                                tableData.push(row);
                            }
                        }
                    }
                    
                    // 生成HTML表格
                    if (tableData.length >= 2) {
                        let html = '<table>';
                        
                        // 表头
                        html += '<thead><tr>';
                        tableData[0].forEach(header => {
                            html += `<th>${escapeHtml(header)}</th>`;
                        });
                        html += '</tr></thead>';
                        
                        // 数据行
                        html += '<tbody>';
                        for (let i = 1; i < tableData.length; i++) {
                            html += '<tr>';
                            tableData[i].forEach(cell => {
                                html += `<td>${escapeHtml(cell)}</td>`;
                            });
                            html += '</tr>';
                        }
                        html += '</tbody></table>';
                        
                        return html;
                    }
                }
                
                return escapeHtml(content);
            } catch (e) {
                console.error('解析简单管道表格失败:', e);
                return escapeHtml(content);
            }
        }

        // HTML转义函数
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // HTML反转义函数
        function unescapeHtml(text) {
            const div = document.createElement('div');
            div.innerHTML = text;
            return div.textContent;
        }

        // 转换markdown图片为HTML图片
        function convertMarkdownImagesToHtml(content) {
            // 先转义HTML以防止XSS攻击
            let processedContent = escapeHtml(content);
            
            // 然后将markdown图片语法转换为HTML图片标签
            processedContent = processedContent.replace(
                /!\[([^\]]*)\]\(([^)]+)\)/g, 
                '<img src="$2" alt="$1" style="max-width: 100%; height: auto; margin: 10px 0; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);" onerror="this.style.display=\'none\'; this.nextSibling.style.display=\'inline\';" /><span style="display: none; color: #666; font-style: italic;">图片加载失败: $1</span>'
            );
            
            return processedContent;
        }

        // 检查内容是否包含表格
        function hasTable(content) {
            // 检查 [表格内容] 标记
            if (content.includes('[表格内容]')) {
                return true;
            }
            
            // 检查标准markdown表格格式
            return /\|(.+)\|\s*\n\|[\s\-\|:]+\|\s*\n/.test(content);
        }

        // 显示结果
        function showResults(result) {
            const resultsDiv = document.getElementById('results');
            const statsDiv = document.getElementById('resultsStats');
            const chunksDiv = document.getElementById('chunksContainer');

            // 显示统计信息
            const avgScore = result.chunks.reduce((sum, chunk) => sum + chunk.semantic_score, 0) / result.chunks.length;
            const avgLength = result.chunks.reduce((sum, chunk) => sum + chunk.content.length, 0) / result.chunks.length;
            const totalTokens = result.chunks.reduce((sum, chunk) => sum + chunk.token_count, 0);

            statsDiv.innerHTML = `
                <div class="stat-item">
                    <div class="stat-value">${result.total_chunks}</div>
                    <div class="stat-label">切片总数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${avgScore.toFixed(2)}</div>
                    <div class="stat-label">平均语义得分</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${Math.round(avgLength)}</div>
                    <div class="stat-label">平均切片长度</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${totalTokens}</div>
                    <div class="stat-label">总Token数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${result.processing_time.toFixed(2)}s</div>
                    <div class="stat-label">处理时间</div>
                </div>
            `;

            // 显示切片结果
            chunksDiv.innerHTML = '';
            result.chunks.forEach((chunk, index) => {
                const chunkCard = document.createElement('div');
                chunkCard.className = 'chunk-card fade-in';
                
                // 检查是否为表格内容
                const isTableContent = chunk.chunk_type === 'table_content' || hasTable(chunk.content);
                // 检查是否包含图片
                const hasImageContent = chunk.content.includes('![') && chunk.content.includes('](');
                
                const contentClass = isTableContent ? 'chunk-content table-content' : 'chunk-content';
                
                // 处理内容显示
                let displayContent = chunk.content;
                let indicator = '';
                
                if (isTableContent) {
                    // 如果是表格内容，转换markdown表格为HTML
                    displayContent = markdownTableToHtml(chunk.content);
                    indicator = '<div class="table-indicator">📊 表格内容</div>';
                } else if (hasImageContent) {
                    // 包含图片，转换markdown图片为HTML图片
                    displayContent = convertMarkdownImagesToHtml(chunk.content);
                    indicator = '<div class="table-indicator" style="background: rgba(34, 139, 34, 0.1); color: #228B22;">🖼️ 图片内容</div>';
                } else {
                    // 对于普通文本内容，确保HTML转义以正确显示换行符
                    displayContent = escapeHtml(chunk.content);
                }
                
                chunkCard.innerHTML = `
                    <div class="chunk-header">
                        <div class="chunk-title">切片 ${index + 1}</div>
                        <div class="chunk-meta">
                            <div class="meta-item">长度: ${chunk.content.length}</div>
                            <div class="meta-item">Token: ${chunk.token_count}</div>
                            <div class="meta-item">类型: ${chunk.chunk_type}</div>
                            <div class="semantic-score">
                                <span>语义得分:</span>
                                <div class="score-bar">
                                    <div class="score-fill" style="width: ${chunk.semantic_score * 100}%"></div>
                                </div>
                                <span>${chunk.semantic_score.toFixed(2)}</span>
                            </div>
                        </div>
                    </div>
                    ${indicator}
                    <div class="${contentClass}">${displayContent}</div>
                `;
                chunksDiv.appendChild(chunkCard);
            });

            resultsDiv.classList.add('show');

            // 滚动到结果区域
            setTimeout(() => {
                resultsDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }, 100);
        }

        // 隐藏结果
        function hideResults() {
            document.getElementById('results').classList.remove('show');
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('AntSK 智能文档切片工具已加载完成');
            
            // 加载默认配置
            loadDefaultConfig();
        });

        // 加载默认配置
        async function loadDefaultConfig() {
            try {
                const response = await fetch('/api/config/default');
                if (response.ok) {
                    const config = await response.json();
                    
                    // 更新配置表单
                    document.getElementById('minChunkSize').value = config.min_chunk_size;
                    document.getElementById('maxChunkSize').value = config.max_chunk_size;
                    document.getElementById('targetChunkSize').value = config.target_chunk_size;
                    document.getElementById('semanticThreshold').value = config.semantic_threshold;
                    // 新增：段落合并阈值
                    if (document.getElementById('paragraphMergeThreshold')) {
                        document.getElementById('paragraphMergeThreshold').value = config.paragraph_merge_threshold ?? 0.8;
                    }
                    document.getElementById('overlapRatio').value = config.overlap_ratio;
                    document.getElementById('language').value = config.language;
                    document.getElementById('preserveStructure').checked = config.preserve_structure;
                    document.getElementById('handleSpecialContent').checked = config.handle_special_content;
                }
            } catch (error) {
                console.warn('无法加载默认配置:', error);
            }
        }
    </script>
</body>
</html>
